<?php

/**
 * 函数库
 * @author HelloWorld
 * 2019-08-14
 * UTF-8
 */
class Lib_Request_Main
{
    private static $obj = NULL;
    private static $appKey = ''; //身份标识
    private static $signKey = ''; //签名秘钥
    private static $dataKey = ''; //数据秘钥
    private static $url = ''; //请求地址
    private static $signature = ''; //签名
    private static $requestId = ''; //请求标识
    private static $method = ''; //请求方法
    private static $timestamp = ''; //请求时间戳


    public function __construct()
    {
        $env = getenv('RUNTIME_ENVIROMENT') ? getenv('RUNTIME_ENVIROMENT') : (defined('SHELL_VARIABLE') ? SHELL_VARIABLE : '');
        $env = empty($env) ? 'local' : $env;
        $config = require(LIBRARY_DIR . '/Conf/' . $env . '/aes.php');
        if (!isset($config)) {
            throw new Exception('can not found the aes env:' . $env . ' $config empty');
        }
        self::$url = $config['url'];
        self::$appKey = $config['appKey'];
        self::$dataKey = $config['dataKey'];
        self::$signKey = $config['signKey'];

    }

    private static function getHeader(){
        return [
            'Content-Type:application/x-www-form-urlencoded',
            "appKey:".self::$appKey,
            "requestId:".self::$requestId,
            "method:".self::$method,
            "timestamp:".self::$timestamp,
            "signature:".self::$signature,
        ];
    }
    private static function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }

    /**
     * 获取单例对象
     * @param string $hl
     * @param number $timeout
     * @return Lib_Request_Main
     */
    public static function getInstance()
    {
        if (is_null(self::$obj)) {
            self::$obj = new self();
        }

        return self::$obj;
    }


    /**
     * @desc  接口请求
     * @param $client
     * @param array $data
     * @param int $timeout
     * @return array
     */
    public function request($url, $data = [], $timeout = 30)
    {
        self::$timestamp = self::getMillisecond();
        self::$requestId = uniqid().mt_rand(1,10000);
        self::$method = $url;
        try {
            $log = "requestId:".self::$requestId;
            $log .= " URL:".self::$url . $url;
            $log .= " DATA:".json_encode($data);
            // 加密json
            $json_data = json_encode($data);
            $aescipher = new Lib_Request_Aes(self::$dataKey);
            $params= $aescipher->encrypt($json_data);
            $log .= " REQUESTDATA:".$params;
            //签名数组
            $sign_data = [
                'method'=>self::$method,
                'requestId'=>self::$requestId,
                'timestamp'=>self::$timestamp,
                'parameters'=>$params,
                'signKey'=>self::$signKey,
            ];
            //获取签名
            self::$signature = Lib_Request_Sign::sign($sign_data);

            //获取header
            $header = self::getHeader();
            $log .= " HEADER:".json_encode(self::getHeader());
            //请求接口
            $params = http_build_query(['requestBody'=>$params]);
            $log .= " PARAM:".$params;
            $result = Lib_Request_Curl::postjson(self::$url, $params, $header, $timeout);
            //链接错误
            $log .= " RESULT:".json_encode($result);
            if($result['error'] != 200){
                $result = ['code' =>$result['error'],'message'=>'链接错误','data'=>[]];
                $log .= " RETURN:".json_encode($result);
                Func_Log::write('request', "REQUEST", $log);
                return $result;
            }
            //返回错误
            if($result['code'] != 0){
                $log .= " RETURN:".json_encode($result);
                Func_Log::write('request', "REQUEST", $log);
                return ['code' =>$result['code'],'message'=>$result['message'],'data'=>[]];
            }
            //返回数据错误
            $data = $result['data'];
            if($data['resultCode'] != "success"){
                $log .= " RETURN:".json_encode($result);
                Func_Log::write('request', "result REQUEST", $log);
                return ['code' =>400,'message'=>$data['detailMessage'],'data'=>[]];
            }
            $data_decrypt = [];
            if (!empty($data['resultData'])) {
                $data_decrypt = json_decode($aescipher->decrypt($data['resultData']), true);
                if($data_decrypt){
                    $result['data'] = $data_decrypt;
                    $log .= " DECYPTDATA:".json_encode($data_decrypt);
                }else{
                    $log .= "decrypt error REPLACEDATA:".json_encode($result);
                    return ['code' =>400,'message'=>"解密失败",'data'=>[]];

                }
            }
            unset($aescipher);
            $env = getenv('RUNTIME_ENVIROMENT') ? getenv('RUNTIME_ENVIROMENT') : (defined('SHELL_VARIABLE') ? SHELL_VARIABLE : '');
            $env = empty($env) ? 'local' : $env;
            if($env == "local" || $env == 'test'){
                Func_Log::write('request', "REQUEST", $log);
            }elseif(!isset($result['data']['code']) || $result['data']['code'] != 0){
                Func_Log::write('request', "REQUEST", $log);
            }
            $str = '{
        "total":0,
        "caseList":[
            {
                "hkfs":"还款方式",
                "yflx":"645.34",
                "fyksbz":"43",
                "qfwyj":"3456.3",
                "qhbj":"1242.5",
                "kfrq":"2019年2月21日",
                "sqje":"23432.4",
                "qfyqlx":"457.62",
                "yqrq":"2019年5月13日",
                "fkje":"345734",
                "yhbj":"1222.3",
                "qkze":"12312.34",
                "yfwyj":"363.93",
                "zclxll":"7%",
                "caseId":"20007",
                "mediationCode":"（2020）陕0112民初诉前调2447号",
                "evidences":[
                    {
                        "fileName":"证据0001",
                        "class":"com.haigui.vilyui.dto.yarlung.FileDTO"
                    }
                ],
                "class":"com.haigui.vilyui.dto.yarlung.CaseDTO",
                "wyxjsbz":"232",
                "applicantName":"测试原告企业",
                "court":"测试法院",
                "qkqsr":"2019年4月22日",
                "jkje":"43736",
                "agents":{
                    "agentNames":"代理人1",
                    "firmName":"测试律师事务所",
                    "class":"com.haigui.vilyui.dto.yarlung.AgentDTO",
                    "relation":"lawyer"
                },
                "respondents":[
                    {
                        "gender":"男",
                        "idCard":"410621199208204574",
                        "mobile":"18801271672",
                        "name":"张强"
                    }
                ],
                "qkzjr":"2019年6月2日",
                "htmcbh":"合同或申请表名称及编号",
                "yqkxll":"9%",
                "yffy":"3458.12",
                "jkqx":"借款期限",
                "qffy":"26.1",
                "qfzclx":"232.52"
            }
        ]
    }';
           // return ['code'=>0,'message'=>'success','data'=>json_decode($str,true)];
            return ['code'=>0,'message'=>'success','data'=>$data_decrypt];
        } catch (Exception $e) {
            Func_Log::write('request', 'WARNING', json_encode($e->getMessage()));
            return ['error' => 500, 'message' => 'link failure', 'data' => []];
        }

    }


}